package com.ostrich.cloud.ostrichOrderService.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ostrich.cloud.common.exceptions.OstrichException;
import com.ostrich.cloud.common.result.PageResult;
import com.ostrich.cloud.ostrichGoodsSercice.model.Dto.GoodsDto;
import com.ostrich.cloud.ostrichGoodsService.client.GoodsClient;
import com.ostrich.cloud.ostrichOrderService.common.OstrichOrderServiceResultCode;
import com.ostrich.cloud.ostrichOrderService.infra.mapper.ShoppingCarGoodsMapper;
import com.ostrich.cloud.ostrichOrderService.infra.model.ShoppingCar;
import com.ostrich.cloud.ostrichOrderService.infra.mapper.ShoppingCarMapper;
import com.ostrich.cloud.ostrichOrderService.infra.model.ShoppingCarGoods;
import com.ostrich.cloud.ostrichOrderService.infra.param.AddGoodsCarParamInfra;
import com.ostrich.cloud.ostrichOrderService.service.service.ShoppingCarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ostrich.cloud.ostrichOrderService.model.dto.ShoppingCarDto;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 购物车id 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2022-10-26
 */
@Service
//@GlobalTransactional(rollbackFor = Exception.class)
@Slf4j
public class ShoppingCarServiceImpl extends ServiceImpl<ShoppingCarMapper, ShoppingCar> implements ShoppingCarService {
    @Resource
    private ShoppingCarMapper carMapper;
    @Resource
    private ShoppingCarGoodsMapper goodsMapper;
    @Resource
    private GoodsClient goodsClient;

    @Override
    public void addGoodsCar(AddGoodsCarParamInfra param)  {
        log.info("param{}",param);
        try{
            // todo 获得用户id选中购物车，如果没有新增
            QueryWrapper<ShoppingCarGoods> wrapper = new QueryWrapper<>();
            wrapper.eq("goods_id",param.getGoodsId());
            ShoppingCarGoods goods = goodsMapper.selectOne(wrapper);
            GoodsDto goodsDto = goodsClient.getGoodsDto(param.getGoodsId());
            QueryWrapper<ShoppingCar> shoppingCarQueryWrapper = new QueryWrapper<>();
            shoppingCarQueryWrapper.eq("customer_id",param.getCustomerId());
            ShoppingCar shoppingCar = carMapper.selectOne(shoppingCarQueryWrapper);
            if (shoppingCar==null){
                ShoppingCar shoppingCar1 = new ShoppingCar();
                shoppingCar1.setCustomerId(param.getCustomerId());
                carMapper.insert(shoppingCar1);
            }
            if (param.getGoodsNumber()>goodsDto.getGoodsStock()){
            throw new OstrichException(OstrichOrderServiceResultCode.NUMBER_ERROR);
            }
            //查询是添加新商品还是修改已有数量

            if (goods!=null){
                goods.setGoodsNum(param.getGoodsNumber());
                goodsMapper.update(goods,wrapper);
            }else {
                // todo 通过goodsId查询商品并添加
                ShoppingCar shoppingCar2 = carMapper.selectOne(shoppingCarQueryWrapper);
                ShoppingCarGoods carGoods = new ShoppingCarGoods();
                carGoods.setGoodsNum(param.getGoodsNumber());
                carGoods.setCarId(shoppingCar2.getCarId());
                carGoods.setGoodsId(param.getGoodsId());
                carGoods.setGoodsNum(param.getGoodsNumber());
                carGoods.setPrice(goodsDto.getGoodsPrice());
                BeanUtil.copyProperties(goodsDto,carGoods);
                int i = goodsMapper.insert(carGoods);
                if (i<1){
                    throw new OstrichException(OstrichOrderServiceResultCode.ADD_ERROR);
                }
            }
        }catch(Exception e){
            try {
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            } catch (TransactionException ex) {
                ex.printStackTrace();
            }
        }

    }

    @Override
    public void delGoodsCar(int customerId,int goodsId,int goodsNum) throws TransactionException {
        // todo 获得用户id并删除两个表的内容
//        try {
            QueryWrapper<ShoppingCar> wrapper = new QueryWrapper<>();
            wrapper.eq("customer_id",customerId);
            ShoppingCar shoppingCar = carMapper.selectOne(wrapper);
            UpdateWrapper<ShoppingCarGoods> shoppingCarUpdateWrapper = new UpdateWrapper<>();
            shoppingCarUpdateWrapper.eq("car_id",shoppingCar.getCarId())
                                    .eq("goods_id",goodsId);
            if (goodsNum==0){
                int delete = goodsMapper.delete(shoppingCarUpdateWrapper);
                if (delete<1){
                    throw new OstrichException(OstrichOrderServiceResultCode.DEL_ERROR);
                }
            }else {
                shoppingCarUpdateWrapper.set("goods_num",goodsNum);
            }

//        }catch(Exception e){
//                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
//        }

    }

    @Override
    public PageResult<ShoppingCarDto> searchCar(Integer customerId, Integer current, Integer size) {
        // todo 获得用户id 查询内容
        QueryWrapper<ShoppingCar> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_id",customerId);
        ShoppingCar shoppingCar = carMapper.selectOne(wrapper);
        PageResult<ShoppingCarDto> goods = null;
        QueryWrapper<ShoppingCarGoods> shoppingCarGoodsQueryWrapper = new QueryWrapper<>();
        shoppingCarGoodsQueryWrapper.eq("car_id",shoppingCar.getCarId());
        Page<ShoppingCarGoods> shoppingCarGoodsPage = goodsMapper.selectPage(new Page<>(current, size), shoppingCarGoodsQueryWrapper);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>shoppingCarGoofsPage{}",shoppingCarGoodsPage);
        if (shoppingCarGoodsPage!=null||shoppingCarGoodsPage.getRecords()!=null){
            List<ShoppingCarDto> shoppingCarDtos = BeanUtil.copyToList(shoppingCarGoodsPage.getRecords(), ShoppingCarDto.class);
            goods = new PageResult<>();
            goods.setElements(shoppingCarDtos);
            goods.setTotalPage(shoppingCarGoodsPage.getPages());
            goods.setTotal(shoppingCarGoodsPage.getTotal());
            goods.setPageSize(shoppingCarGoodsPage.getSize());
            goods.setPage(shoppingCarGoodsPage.getCurrent());
            log.info("<<<<<<<<<<<<<<<<<<<<<<goods{}",goods);
        }
        return goods;
    }
}
